package vn.vfriends.id.util;

import java.io.IOException;
import java.io.StringWriter;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tuan@vfriends.vn
 */
public class XrdsDocumentBuilder {

    private static final Logger logger = LoggerFactory.getLogger(XrdsDocumentBuilder.class);
    private Element baseElement;
    private static final String MASTER_XRDS_NAMESPACE = "xri://$xrd*($v*2.0)";

    public XrdsDocumentBuilder() {
        Namespace xrdNS = Namespace.getNamespace(MASTER_XRDS_NAMESPACE);
        baseElement = new Element("XRD", xrdNS);
    }

    public void addServiceElement(String type, String uri, String priority) {
        addServiceElement(type, uri, priority, null);
    }

    private void addServiceElement(String type, String uri, String priority, String delegate) {
        logger.debug("Creating service element of type '" + type + "' for uri '" + uri + "' of priority '" + priority + "' with delegate '" + delegate + "'");
        Namespace xrdNS = Namespace.getNamespace(MASTER_XRDS_NAMESPACE);
        Namespace openidNS = Namespace.getNamespace("openid", "http://openid.net/xmlns/1.0");
        Element serviceElement = new Element("Service", xrdNS);
        Element typeElement = new Element("Type", xrdNS);
        typeElement.addContent(type);
        Element uriElement = new Element("URI", xrdNS);
        uriElement.addContent(uri);
        serviceElement.addContent(typeElement);
        serviceElement.addContent(uriElement);
        if (!StringUtil.isEmpty(delegate)) {
            Element delegateElement = new Element("Delegate", openidNS);
            delegateElement.addContent(delegate);
            serviceElement.addContent(delegateElement);
        }
        if (!StringUtil.isEmpty(priority)) {
            serviceElement.setAttribute("priority", priority);
        }
        baseElement.addContent(serviceElement);
    }

    public String toXmlString() {
        Namespace xrdsNS = Namespace.getNamespace("xrds", "xri://$xrds");
        Element rootElement = new Element("XRDS", xrdsNS);
        rootElement.addContent(baseElement);
        Document doc = new Document(rootElement);
        StringWriter w = new StringWriter();
        XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
        try {
            o.output(doc, w);
            w.close();
        } catch (IOException e) {
            logger.warn("Caught an IOException while writing to StringWriter! This can't be happening!", e);
        }
        logger.debug("XRD Response = " + w.toString());
        return w.toString();
    }
}
